import pandas as pd
from datetime import datetime
import pickle as pk
import json
import glob
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.lines as mlines
import seaborn as sns
import numpy as np

c = 1000

label_fontsize = 40
tick_fontsize = 20

dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d')

#########################################################################
# Individual time-series of top narratives (grid format)

df = pd.read_csv('../data/gpo_final_data/narratives_complete_with_metadata_manual_labels_rich_{0}.csv'.format(c), parse_dates=['date'], date_parser=dateparse)

# save in a text file for the appendix
with open('../tables/Section_K.tex', 'w') as f:
     for narrative in list(df.narrative.value_counts().reset_index()['index']): 
          f.write(narrative + ', ' + '\n')

df['year'] = df['date'].dt.year

years = pd.DataFrame(set(df["year"]))
years.columns = ['year']

df = df.sort_values(by = 'frequency', ascending = False)

narratives = list(df.drop_duplicates(subset = 'narrative')['narrative'])

fig = plt.figure(figsize = (60,60))
fig.subplots_adjust(hspace=0.4, wspace=0.4)

for i in range(1,19):
    narrative = narratives[i-1]
    _top_narratives_grouped = df[df['narrative'] == narrative].groupby(['year']).count()['n'].reset_index()
    _top_narratives_grouped = _top_narratives_grouped.merge(years, on = 'year', how = 'outer')
    _top_narratives_grouped = _top_narratives_grouped.fillna(0)
    _ax = fig.add_subplot(6,3,i)
    _ax.set_title(narrative + "\n",fontsize= label_fontsize)
    _ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    _ax.xaxis.label.set_fontsize(label_fontsize)
    _ax.set_xlabel(' ')
    _ax.yaxis.label.set_fontsize(label_fontsize)
    _ax.set_ylabel(' ')
    _ax.set_facecolor((.18, .31, .31, 0.0))
    _ax.grid(color='#dfede2')
    _g = sns.lineplot(
    data=_top_narratives_grouped,
    x = 'year',
    y = 'n',
    markers = True,
    dashes = False,
    ax=_ax,
    markersize=15,
    linewidth=2.5)
    plt.xticks(range(1994,2015,5), fontsize=tick_fontsize)
    plt.yticks(fontsize=tick_fontsize)
    
fig.savefig('../figures/Figure_G_1.pdf'.format(c))
